from django.shortcuts import render
from rest_framework.pagination import PageNumberPagination
# Create your views here.
from django.contrib.auth.models import Group,User
from rest_framework import permissions,pagination
from .serializer import *
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import *
from rest_framework import viewsets, mixins, permissions,generics
from elasticsearch_dsl.query import MultiMatch, Match
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search,Index,connections,Q,A

connections.create_connection(alias='es_connection', hosts=['localhost:9200'], timeout=60)


class IsIndexOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.user.username == "root":
            return True
        else:
            user_groups = Group.objects.filter(user__username=request.user).all()
            user_indices = Indexes.objects.filter(groups__in=user_groups)
            if obj.index_name in list(set([x.index_name for x in user_indices])):
                return True
            else:
                return False

class IndexListView(generics.ListAPIView):
    serializer_class = IndexesSerializer
    queryset = Indexes.objects.all()

    def get(self, request, *args, **kwargs):
        user_groups = Group.objects.filter(user__username=request.user).all()
        print(request.user)
        user_indices = Indexes.objects.filter(groups__in=user_groups)
        serializer = self.get_serializer(user_indices, many=True)

        return Response(serializer.data)

class HeaderView(generics.RetrieveAPIView):
    serializer_class = IndexSerializer
    queryset = Indexes.objects.all()
    # permission_classes = [IsIndexOwnerOrReadOnly]

    def get(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.resp = {}
        s = Search(using="es_connection", index=instance.index_name + '*').query()[0:1]
        query_resp = s.execute().to_dict()['hits']['hits']
        print(query_resp)
        instance.resp = {}
        if len(query_resp) != 0:
            instance.resp = query_resp[0]
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

class LogDetailView(generics.RetrieveAPIView):
    serializer_class = IndexSerializer
    queryset = Indexes.objects.all()
    permission_classes = [IsIndexOwnerOrReadOnly]

    def get(self, request, *args, **kwargs):
        #Pagination
        page = int(request.GET.get('page', '1'))
        itemsPerPage = int(request.GET.get('itemsPerPage', '10'))
        keywords = str(request.GET.get('keywords'))
        search_fields = request.GET.get('search_fields')
        starttime = request.GET.get('starttime')
        endtime = request.GET.get('endtime')
        sortBy = request.GET.get('sortBy')
        sortDesc = request.GET.get('sortDesc')
        start = (page - 1) * itemsPerPage
        end = start + itemsPerPage
        fields = search_fields.split(",")
        seq = 'asc'
        if sortDesc == "true":
            seq = 'desc'
        #Merge ES Query to the Instance
        instance = self.get_object()
        dsl = Q("multi_match", query=keywords, fields=fields, fuzziness='AUTO')
        s = Search(using="es_connection", index=instance.index_name + '*').query(dsl)[start:end]
        if sortBy != None:
            s = s.sort({sortBy : {"order": seq }})
        s = s.filter('range', **{"ingest_timestamp": {'gte': starttime, 'lt': endtime, 'format': 'epoch_millis'}})
        s.aggs.bucket('by_time','date_histogram', field='ingest_timestamp', fixed_interval='30m')
        query_resp = s.execute().to_dict()
        instance.resp = query_resp
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

        # dsl = Q("match", project=instance.name)
        # s = Search(using="es_connection", index='goodbye-2021.09.14-1').query(dsl)
        # response = s.execute()
        # dict = {'response': response.to_dict(),'groups': [1]}
        # return self.retrieve(request, *args, **kwargs)




